/***** BEGIN LICENSE BLOCK *****
 Version: MPL 1.1
 
 The contents of this file are subject to the Mozilla Public License Version 
 1.1 (the "License"); you may not use this file except in compliance with 
 the License. You may obtain a copy of the License at 
 http://www.mozilla.org/MPL/
 
 Software distributed under the License is distributed on an "AS IS" basis,
 WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 for the specific language governing rights and limitations under the
 License.
 
 The Original Code is GureGipuzkoa Extension.
 
 The Initial Developer of the Original Code is Asier Sarasua Garmendia.
 Portions created by the Initial Developer are Copyright (C) 2009
 the Initial Developer. All Rights Reserved.
 
 Contributor(s):
    Asier Sarasua Garmendia <asier.sarasua@gmail.com>
    Julen Ruiz Aizpuru <julenx@gmail.com>
    Juanan Pereira <juanan@diariolinux.com>
 
 ***** END LICENSE BLOCK *****/

const gureGipuzkoa = {
  uid: "guregipuzkoa@guregipuzkoa.net",

  username: "",

  password: "",

  //apiKey: "", Asier: if I use this variable, the search doesn't work

  token: "",

  baseURL: "http://api.guregipuzkoa.net",

  photoURL: "http://www.guregipuzkoa.net/photo/",

  restURL: "http://api.guregipuzkoa.net/services/rest/",

  uploadURL: "http://api.guregipuzkoa.net/services/upload/",

  licenseURL: "http://www.guregipuzkoa.net/info/cc.php",

  apiCallURL:
    function(params, url) {
      params.key = gureGipuzkoaUtils.prefManager.getCharPref("guregipuzkoa.user.apikey");
      var pp = new Array();
      for (var p in params) {
        pp.push(p);
      }
      var callURL = (url ? url : gureGipuzkoa.restURL ) + '?';
      for (var p in pp.sort()) {
        var pn = pp[p];
        callURL += pn + '=' + params[pn] + '&';
      }
      return callURL;
  },

  apiCall:
    function(params, onSuccess, onFailure) {
      var ggXHR = new XMLHttpRequest();
      ggXHR.open("GET", gureGipuzkoa.apiCallURL(params));
      ggXHR.onreadystatechange = function() {
        if (ggXHR.readyState != 4)
          return false;
        if (ggXHR.status == 200) {
          var stat = ggXHR.responseXML.firstChild.getAttribute('stat');
          if (stat == 'ok') {
            if (onSuccess) {
              onSuccess(ggXHR);
            }
          } else {
            gureGipuzkoaUtils.errorDumpXHR(ggXHR.responseXML, params.method);
            if (onFailure)
              onFailure(ggXHR, stat, eCode, eMsg);
          }
        } else {
          gureGipuzkoaUtils.errorDumpXHR(ggXHR.responseXML, params.method);
          if (onFailure) {
            onFailure(ggXHR);
          }
        }
        return true;
      }
      try {
        ggXHR.send(null);
      } catch(e) {}
      return true;
  },

  /* Calls the API's getToken method and stores the result in gureGipuzkoa.token
   */
  getToken:
    function() {
      gureGipuzkoa.apiCall(
        { method: 'gg.auth.getToken',
          username: gureGipuzkoa.username,
          password: gureGipuzkoa.password },
        function(xhr) {
          // Store token for later use
          gureGipuzkoa.token = xhr.responseXML.getElementsByTagName("token")[0]
                                              .textContent.replace(/ /g, "")
                                              .replace("\n", "");
        },
        function() {
        }
     );
  },

  /* Based on Fireflix upload code:
   * http://git.klever.net/view/cgit/kin/fireflix.git/tree/content/flickr.js#n284
   */
  uploadFile:
    function(filePath, params, onSuccess, onFailure, index) {
      try {
        var fi = Components.classes["@mozilla.org/file/local;1"]
                           .createInstance(Components.interfaces.nsILocalFile);
        fi.initWithPath(filePath);

        var st = Components.classes["@mozilla.org/network/file-input-stream;1"]
                           .createInstance(Components.interfaces.nsIFileInputStream);
        st.init(fi, 0x01, 00004, null);

        var bis = Components.classes["@mozilla.org/binaryinputstream;1"]
                            .createInstance(Components.interfaces.nsIBinaryInputStream);
        bis.setInputStream(st);

        // allocate and initialize temp storage string
        var pbs = Components.classes["@mozilla.org/storagestream;1"]
                            .createInstance(Components.interfaces.nsIStorageStream);
        pbs.init(1024, 10000000, null);

        // create output stream
        var pbos = pbs.getOutputStream(0);
        // and a binaryoutputstream interface
        var pbbos = Components.classes["@mozilla.org/binaryoutputstream;1"]
                              .createInstance(Components.interfaces.nsIBinaryOutputStream);
        pbbos.setOutputStream(pbos);

        // create POST body
        var boundaryToken = 'kadaroloongazaduviaxamma';
        var boundary = '--' + boundaryToken;
        var b = '';

        var args = { key: gureGipuzkoa.apiKey,
                     token: gureGipuzkoa.token };
        for (var p in params)
          args[p] = params[p];

        var pns = new Array();
        for (var p in args)
          pns.push(p);

        for (var p in pns.sort()) {
          var pn = pns[p];
          b += boundary + '\nContent-Disposition: form-data; name="' + pn +
               '"\n\n' + gureGipuzkoaStrUtils.stringToUTF8(args[pn]) + '\n';
        }
        b += boundary + '\nContent-Disposition: form-data; name="photo"; filename="' +
             filePath + '"\nContent-Type: image/jpeg\nContent-Transfer-Encoding: binary\n\n';
        pbbos.writeBytes(b, b.length);

        // write binary input stream + boundary
        var bisbytes = bis.available();
        pbbos.writeBytes(bis.readBytes(bisbytes), bisbytes);
        pbbos.writeBytes('\n' + boundary + '--', 3 + boundary.length);

        bis.close();
        st.close();
        pbbos.close();
        pbos.close();

        var ggXHR = new XMLHttpRequest();
        ggXHR.open("POST", this.uploadURL);
        ggXHR.setRequestHeader('Content-Type', 'multipart/form-data; boundary="' + boundaryToken + '"');
        ggXHR.setRequestHeader('Connection', 'close');
        ggXHR.setRequestHeader('Content-Length', b.length);
        ggXHR.onreadystatechange = function() {
          if (ggXHR.readyState != 4)
            return false;
          if (ggXHR.status == 200) {
            var stat = ggXHR.responseXML.firstChild.getAttribute('stat');
            if (stat == 'ok') {
              if (onSuccess)
                onSuccess(index);
            } else {
              gureGipuzkoaUtils.errorDumpXHR(ggXHR.responseXML);
              if (onFailure)
                onFailure(index);
            }
          } else {
            gureGipuzkoaUtils.errorDumpXHR(ggXHR.responseXML);
            if (onFailure)
              onFailure(index);
          }
          return true;
        };
        ggXHR.send(pbs.newInputStream(0));
      } catch(e) {
        dump('upload failed: ' + e.message + '\n');
        if (onFailure)
          onFailure(index);
      }

  },

  openPrefs:
    function() {
      var dialogURL = "chrome://guregipuzkoa/content/prefs.xul";
      window.openDialog(dialogURL, "", "chrome,modal,close");
    },

  openHelp:
    function(url) {
      gureGipuzkoaUIUtils.useTab(url);
    },

}
